package com.such.kit.remote;

import java.net.InetAddress;
import java.net.UnknownHostException;
import jakarta.servlet.http.HttpServletRequest;
import com.such.kit.Logger;
import com.such.kit.validate.ValidateCommons;

/**
 * @author SUCH
 * <pre>
 * URL 请求模拟工具
 * </pre>
 */
public class RemoteCommons {

	/**
	 * <pre>
	 * 获取远程 ip
	 * </pre>
	 * @param request http 请求
	 * @return 远程 ip
	 */
	public static String getRemoteIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ValidateCommons.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ValidateCommons.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ValidateCommons.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			if (ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")) {
				try {
					// 取本地 ip
					ip = InetAddress.getLocalHost().getHostAddress();
				} catch (UnknownHostException e) {
					Logger.warn(RemoteCommons.class, "获取本地 ip 异常", e);
				}
			}
		}
		if (ValidateCommons.isNotEmpty(ip)) {
			/*
			处理代理
			多个代理 ip 以 "," 分割
			第 1 个为客户端真实 ip
			*/
			int index = ip.indexOf(",");
			if (index > 0) {
				ip = ip.substring(0, index);
			}
		}
		return ip;
	}

}
